package com.xc.service.impl;

import com.xc.dto.ResultDTO;
import com.xc.dto.UserDTO;
import com.xc.entity.UserEntity;
import com.xc.entity.UserRoleEntity;
import com.xc.entity.UserRoleManyEntity;
import com.xc.mapper.UserMapper;
import com.xc.mapper.UserRoleMapper;
import com.xc.service.UserRoleService;
import com.xc.service.UserService;
import com.xc.util.JSONCopy;
import com.xc.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public ResultDTO add(UserRoleEntity userRoleEntity) {
        return ResultDTO.builder()
                .code(0)
                .count(userRoleMapper.add(userRoleEntity))
                .build();
    }

    /**
     * 更新用户角色，如果
     *
     * @param userRoleEntity
     * @return
     */
    @Override
    public ResultDTO update(UserRoleEntity userRoleEntity) {
        if (userRoleEntity.getId() == null) {
            return add(userRoleEntity);
        }
        return ResultDTO.builder()
                .code(0)
                .count(userRoleMapper.update(userRoleEntity))
                .build();
    }

    @Override
    public ResultDTO delete(UserRoleEntity userRoleEntity) {
        return ResultDTO.builder()
                .code(0)
                .count(userRoleMapper.delete(userRoleEntity))
                .build();
    }

    @Override
    public ResultDTO updateEnable(UserRoleEntity userRoleEntity) {
        return ResultDTO.builder()
                .code(0)
                .count(userRoleMapper.updateEnable(userRoleEntity))
                .build();
    }

    @Override
    public ResultDTO findById(UserRoleEntity userRoleEntity) {
        return ResultDTO.builder()
                .code(0)
                .count(0)
                .data(userRoleMapper.findById(userRoleEntity))
                .build();
    }

    @Override
    public ResultDTO findAll(UserRoleEntity userRoleEntity) {
        return ResultDTO.data(userRoleMapper.count(userRoleEntity), userRoleMapper.findAll(userRoleEntity));
    }

    @Override
    public ResultDTO count(UserRoleEntity userRoleEntity) {
        return ResultDTO.data(userRoleMapper.count(userRoleEntity));
    }

    @Override
    public ResultDTO findByName(UserRoleEntity userRoleEntity) {
        return null;
    }

    @Override
    public ResultDTO addMany(List<UserRoleManyEntity> list) {
        List<Integer> ids = new ArrayList<>();
        list.forEach((item) -> ids.add(item.getUserId()));
        userRoleMapper.deleteByUserId(ids);
        return ResultDTO.data(userRoleMapper.addMany(list));
    }

    @Override
    public ResultDTO findByUserId(UserRoleEntity userRoleEntity) {
        return ResultDTO.data(userRoleMapper.findByUserId(userRoleEntity));

    }
}
